package com.xc.sys.controller;

import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.tool.Helper;
import com.xc.db.tables.SysRole;
import com.xc.db.tables.SysRoleNavi;
import com.xc.sys.entity.SysOrganizationEntity;
import com.xc.sys.entity.SysRoleEntity;
import com.xc.sys.entity.SysRoleNaviEntity;
import com.xc.sys.entity.SysUserEntity;
import com.xc.sys.service.SysOrganizationService;
import com.xc.sys.service.SysRoleNaviService;
import com.xc.sys.service.SysRoleService;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping({ "/role" })
public class SysRoleController {
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleNaviService sysRoleNaviService;
	@Autowired
	private SysUserService sysUserService;
	private SysRole SYSROLETB = SysRole.SYS_ROLE.as("SYSROLETB");
	private SysRoleNavi SYSROLENAVITB = SysRoleNavi.SYS_ROLE_NAVI.as("SYSROLENAVITB");
	@RequestMapping({ "/getPageList" })
	public LayuiTableResponse<SysRoleEntity> getPageList(SysRoleEntity entity, Integer limit, Integer page,
			HttpServletRequest request) {
		LayuiTableResponse<SysRoleEntity> ltr = new LayuiTableResponse<>();
		Condition cond = SYSROLETB.ID.isNotNull();
		SysUserEntity me = Helper.getMe(request);
		String name = request.getParameter("name");
		String orgId = request.getParameter("orgId");
		if(StringUtils.isNotEmpty(name)) {
			cond = DSL.or(SYSROLETB.NAME.like("%"+name+"%"),SYSROLETB.CODE.like("%"+name+"%"));
		}
		if(StringUtils.isNotEmpty(orgId)) {
			//cond = cond.and(SYSROLETB.ORG_ID.eq(orgId));
		}
		Long count = sysRoleService.count(cond);
		PageInfo<SysRoleEntity> pageInfo = new PageInfo<>(limit, page);
		ltr.setCount(count);
		sysRoleService.select(cond, pageInfo, SYSROLETB.ORDERNO.asc());
		for(SysRoleEntity bt : pageInfo.getList()){
			setTxt(bt);
		}
		ltr.setData(pageInfo.getList());
		return ltr;
	}
	private void setTxt(SysRoleEntity bt) {
		SysUserEntity u = sysUserService.getEntityById(bt.getCreateUserId());
		bt.setCreateUserId(u==null?"":u.getName());
		if(bt.getOrgId()!=null&&!bt.getOrgId().equals("")) {
			SysOrganizationEntity orgentity = SysOrganizationService.getFromCaches(bt.getOrgId());
			bt.setOrgName(orgentity==null?"":orgentity.getShortName());
		}
	}
	@RequestMapping({ "/getList" })
	public LayuiTableResponse<SysRoleEntity> getList(SysRoleEntity entity, Integer limit, Integer page,
			HttpServletRequest request) {
		LayuiTableResponse<SysRoleEntity> ltr = new LayuiTableResponse<>();
		Condition cond = SYSROLETB.ID.isNotNull();
		List<SysRoleEntity> list = sysRoleService.select(cond, SYSROLETB.NAME.asc());
		ltr.setData(list);
		return ltr;
	}
	
	@RequestMapping({ "/getPageListExcludeAssigned" })
	public LayuiTableResponse<SysRoleEntity> getPageListExcludeAssigned(SysRoleEntity entity, Integer limit, Integer page,
			HttpServletRequest request) {
		SysUserEntity me = Helper.getMe(request);
		String userId = request.getParameter("userId");
		String excludeIdstring = request.getParameter("excludeIds");
		String excludeCode = request.getParameter("excludeCodes");
		LayuiTableResponse<SysRoleEntity> ltr = new LayuiTableResponse<>();
		Condition cond = SYSROLETB.ID.isNotNull();
		List<SysRoleEntity> existList = new ArrayList<>();
		if(StringUtils.isNotEmpty(userId)&&!userId.equals("null")) {
			SysUserVO user = SysUserService.getFrameCaches(userId);
			if(user.getRoleCode()!=null&&!user.getRoleCode().isEmpty()) {
				String[] posts = StringUtils.split(user.getRoleCode(),",");
				existList = sysRoleService.select(SYSROLETB.CODE.in(posts));
				cond = cond.and(SYSROLETB.CODE.notIn(posts));
			}
			
		}
		if(StringUtils.isNotEmpty(entity.getName())) {
			cond = cond.and(DSL.or(SYSROLETB.NAME.like("%"+entity.getName()+"%"),SYSROLETB.CODE.like("%"+entity.getName()+"%")));
		}
		if(StringUtils.isNotEmpty(excludeIdstring)) {
			cond = cond.and(SYSROLETB.ID.notIn(Helper.covertArr2Ls(excludeIdstring)));
		}
		if(StringUtils.isNotEmpty(excludeCode)) {
			String[] excludeCodes = StringUtils.split(excludeCode,",");
			cond = cond.and(SYSROLETB.CODE.notIn(excludeCodes));
		}
		Long count = sysRoleService.count(cond);
		PageInfo<SysRoleEntity> pageInfo = new PageInfo<>(limit, page);
		ltr.setCount(count);
		sysRoleService.select(cond, pageInfo, SYSROLETB.ORDERNO.asc(),SYSROLETB.NAME.asc());
		for(SysRoleEntity bt : pageInfo.getList()){
			setTxt(bt);
		}
		ltr.setData(pageInfo.getList());
		ltr.setData2(existList);
		return ltr;
	}
	@RequestMapping({ "/getPageListAssigned" })
	public LayuiTableResponse<SysRoleEntity> getPageListAssigned(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		String roleCode = request.getParameter("roleCode");
		String idstring = request.getParameter("ids");
		LayuiTableResponse<SysRoleEntity> ltr = new LayuiTableResponse<>();
		Condition cond = SYSROLETB.ID.isNotNull();
		if (StringUtils.isNotEmpty(userId)) {
			SysUserVO user = SysUserService.getFrameCaches(userId);
			if(user.getRoleCode()!=null&&!user.getRoleCode().isEmpty()) {
				String[] posts = StringUtils.split(user.getRoleCode(),",");
				cond = cond.and(SYSROLETB.CODE.in(posts));
			}else {
				cond = cond.and(SYSROLETB.CODE.eq("#"));
			}
		}
		if (StringUtils.isNotEmpty(idstring)) {
			cond = cond.and(SYSROLETB.ID.in(Helper.covertArr2Ls(idstring)));
		}
		if (StringUtils.isNotEmpty(roleCode)) {
			String[] roleCodes = StringUtils.split(roleCode,",");
			cond = cond.and(SYSROLETB.CODE.in(roleCodes));
		}
		List<SysRoleEntity> list = sysRoleService.select(cond, SYSROLETB.ORDERNO.asc(),SYSROLETB.NAME.asc());
		for (SysRoleEntity bt : list) {
			setTxt(bt);
		}
		ltr.setData(list);
		return ltr;
	}
	@RequestMapping({ "/getRoleNaviList" })
	public LayuiTableResponse<SysRoleNaviEntity> getRoleNaviList(Long roleId) {
		LayuiTableResponse<SysRoleNaviEntity> ltr = new LayuiTableResponse<>();
		SysRoleEntity roleEntity = sysRoleService.getEntityById(roleId);
		List<SysRoleNaviEntity> list = new ArrayList<>();
		if(roleEntity==null) {
			return ltr;
		}
		list = sysRoleNaviService.select(SYSROLENAVITB.ROLE_CODE.eq(roleEntity.getCode()), SYSROLENAVITB.NAVI_ID.asc());
		ltr.setData(list);
		return ltr;
	}
	@RequestMapping({ "/getById" })
	public SysRoleEntity getById(Long id) {
		SysRoleEntity entity = sysRoleService.getEntityById(id);
		return entity;
	}
	@RequestMapping({ "/assignNavis" })
	public LayuiTableResponse<String> assignNavis(String roleCode, @RequestParam("naviIds[]") String[] naviIds,
			HttpServletRequest request) {
		SysUserEntity me = Helper.getMe(request);
		LayuiTableResponse<String> ltr = new LayuiTableResponse<>();
		sysRoleNaviService.deleteByRoleCode(roleCode);
		for (String naviId : naviIds) {
			SysRoleNaviEntity oe = new SysRoleNaviEntity();
			oe.setCreateTime(new Date());
			oe.setCreateUserId(me.getId());
			oe.setRoleCode(roleCode);
			oe.setNaviId(naviId);
			sysRoleNaviService.insert(oe);
		}
		return ltr;
	}

	@RequestMapping({ "/save" })
	public ResponseEntity<SysRoleEntity> save(@RequestBody SysRoleEntity entity,HttpServletRequest request) {
		SysUserEntity me = Helper.getMe(request);
		ResponseEntity<SysRoleEntity> res = new ResponseEntity<>();
		res.setCode(0);
		if(StringUtils.isEmpty(entity.getId())){
			entity.setCreateTime(new Date());
			entity.setCreateUserId(me.getId());
			Long count = sysRoleService.count(SYSROLETB.CODE.eq(entity.getCode()).and(SYSROLETB.ORG_ID.eq(me.getOrgId())));
			if(count>0) {
				res.setCode(1);
				res.setMsg("岗位编码已存在，请仔细检查");
				return res;
			}
			count = sysRoleService.count(SYSROLETB.NAME.eq(entity.getName()).and(SYSROLETB.ORG_ID.eq(me.getOrgId())));
			if(count>0) {
				res.setCode(1);
				res.setMsg("岗位名称已存在，请仔细检查");
				return res;
			}
		}else {
			SysRoleEntity obj = sysRoleService.getEntityById(Long.valueOf(entity.getId()));
			entity.setCreateTime(obj.getCreateTime());
			entity.setCreateUserId(obj.getCreateUserId());
			Long count = sysRoleService.count(SYSROLETB.CODE.eq(entity.getCode()).and(SYSROLETB.ID.notEqual(Long.valueOf(entity.getId()))).and(SYSROLETB.ORG_ID.eq(me.getOrgId())));
			if(count>0) {
				res.setCode(1);
				res.setMsg("岗位编码已存在，请仔细检查");
				return res;
			}
			count = sysRoleService.count(SYSROLETB.NAME.eq(entity.getName()).and(SYSROLETB.ID.notEqual(Long.valueOf(entity.getId())).and(SYSROLETB.ORG_ID.eq(me.getOrgId()))));
			if(count>0) {
				res.setCode(1);
				res.setMsg("岗位名称已存在，请仔细检查");
				return res;
			}
		}
		sysRoleService.save(entity);
		return res;
	}

	@RequestMapping({ "/delete" })
	public LayuiTableResponse<SysRoleEntity> delete(@RequestParam("ids[]") Long[] ids) {
		LayuiTableResponse<SysRoleEntity> ltr = new LayuiTableResponse<>();
		for (Long id : ids) {
			sysRoleService.deleteById(id);
		}
		return ltr;
	}
}
